package view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class CameraView extends SurfaceView implements SurfaceHolder.Callback 
{
	private static final String TAG = CameraView.class.getSimpleName();
	
	private SurfaceHolder _surfaceHolder;
	
	private Scanner _context;
	
	//Draw coordinates
	private float[] _points;
	private Paint _paint;

	public CameraView(Context context, AttributeSet attrs) 
	{
		super(context, attrs);
		
		_context = (Scanner) context;
		_surfaceHolder = getHolder();
		_surfaceHolder.addCallback(this);
		
		_points = new float[0];
		
		//Draw coordinates of referencepoints
		_paint = new Paint();
		_paint.setColor(Color.BLUE);
		_paint.setStrokeWidth(20);
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) 
	{
		Log.d(TAG, String.format("surfaceChanged()"));
		setWillNotDraw(false);
		
		_surfaceHolder = holder;
		_context.startCamera(_surfaceHolder);
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) 
	{
		Log.d(TAG, String.format("SurfaceCreated()"));
		
		setWillNotDraw(false);
		_surfaceHolder = holder;
		_context.startCamera(_surfaceHolder);
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) 
	{
		Log.d(TAG, "SurfaceDestroyed()");
		if(_surfaceHolder.getSurface() == null)
			return;
	}
	
	/**
	 * Set coordinates of referencepoints and draw them accordingly
	 * @param points coordinates of reference points
	 */
	public void setPoints(float[] points)
	{
//		Log.d(TAG, String.format("setPoints() - points: %d", points.length));
		_points = points;
		
		setWillNotDraw(false);
		
		invalidate();
	}
	
	@Override
	protected void onDraw(Canvas canvas) 
	{
//		Log.d("TAG", String.format("onDraw - _points: %d", _points.length));
		if(_points != null && _points.length != 0)
			canvas.drawPoints(_points, _paint);
	}
}
